﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;
using System.Collections.ObjectModel;
using CookComputing.XmlRpc;
using System.Reflection;
using System.Threading;
using System.IO;
using Microsoft.Phone.Marketplace;
using Microsoft.Phone.Net;



namespace HomeWP
{
    public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
    {
        // Data context for the local database
        private HMDataContext hMDB;

        // Define an observable collection property that controls can bind to.
        private ObservableCollection<Device> _hMDevices;
        private ObservableCollection<SystemVariable> _hMVariables;


        public ObservableCollection<Device> HMDevices
        {
            get
            {
                return _hMDevices;
            }
            set
            {
                if (_hMDevices != value)
                {
                    _hMDevices = value;
                    NotifyPropertyChanged("HMDevices");
                }
            }
        }

        public ObservableCollection<SystemVariable> HMVariables
        {
            get
            {
                return _hMVariables;
            }
            set
            {
                if (_hMVariables != value)
                {
                    _hMVariables = value;
                    NotifyPropertyChanged("HMVariable");
                }
            }
        }

        private static LicenseInformation _licenseInfo = new LicenseInformation();

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            
            // Create the database if it does not exist.
            using (HMDataContext db = new HMDataContext(HMDataContext.DBConnectionString))
            {
                if (db.DatabaseExists() == false)
                {
                    //Create the database
                    db.CreateDatabase();
                }
            }

            // Connect to the database and instantiate data context.
            hMDB = new HMDataContext(HMDataContext.DBConnectionString);

            // Data context and observable collection are children of the main page.
            this.DataContext = this;

            tB_PleaseWait.Visibility = System.Windows.Visibility.Collapsed;

        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                // Define the query to gather all of the to-do items.
                var HMItemsInDB = from Device todo in hMDB.HMDevices select todo;

                // Execute the query and place the results into a collection.
                HMDevices = new ObservableCollection<Device>(from Device oItem in hMDB.HMDevices select oItem);
                HMVariables = new ObservableCollection<SystemVariable>(from SystemVariable oItem in hMDB.HMVariables_ select oItem);

                //HMDeviceNames = new ObservableCollection<DeviceName>(from DeviceName oItem in hMDB.HMDeviceName select oItem);

                if (hMDB.HMCCUSettings.Count(t => t.ConfigID == "TEST") > 0)
                {
                    CCUSettings CCUSet = hMDB.HMCCUSettings.Single(t => t.ConfigID == "TEST");
                    if (string.IsNullOrEmpty(CCUSet.CCU))
                        TB_CCUAddress.IsEnabled = true;
                    else
                    {
                        TB_CCUAddress.Text = CCUSet.CCU;
                    }
                }


                // Call the base method.
                base.OnNavigatedTo(e);
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            // Call the base method.
            base.OnNavigatedFrom(e);

            // Save changes to the database.
            try
            {
                hMDB.SubmitChanges();
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Devices.xaml", UriKind.Relative));
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify Silverlight that a property has changed.
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        public class HMDataContext : DataContext
        {
            // Specify the connection string as a static, used in main page and app.xaml.
            public static string DBConnectionString = "Data Source=isostore:/HM.sdf";

            // Pass the connection string to the base class.
            public HMDataContext(string connectionString)
                : base(connectionString)
            { }

            // Specify a single table for the to-do items.
            public Table<Device> HMDevices;
            public Table<Children> HMChildren;
            public Table<DeviceRoom> HMRoom;
            public Table<DeviceFunction> HMFunction;
            public Table<ParamSet> HMParamSet;
            public Table<CCUSettings> HMCCUSettings;
            public Table<SystemVariable> HMVariables_;
        }

        public Homematic proxy;
        

        [XmlRpcUrl(Homematic.UrlCCU)]
        public class Homematic : XmlRpcClientProtocol
        {
            public const string UrlCCU = "http://192.168.2.15:2001";

            [XmlRpcBegin("listDevices")]
            public IAsyncResult ListDevices(AsyncCallback acb)
            {
                this.ResponseEvent += new XmlRpcResponseEventHandler(Homematic_ResponseEvent);
                return this.BeginInvoke(MethodBase.GetCurrentMethod(), new object[] { }, acb, null);
            }

            public string GetStringFromStream(Stream stream)
            {
                // Create a stream reader.
                using (StreamReader reader = new StreamReader(stream))
                {
                    // Just read to the end.
                    return reader.ReadToEnd();
                }
            }

            void Homematic_ResponseEvent(object sender, XmlRpcResponseEventArgs args)
            {
                if (this.Finished != null)
                    this.Finished.Invoke(sender, new EventArgs());
            }

            public event EventHandler Finished;


            [XmlRpcEnd]
            public XmlRpcStruct[] EndListDevicesGet(IAsyncResult iasr)
            {
                XmlRpcStruct[] ret = (XmlRpcStruct[])this.EndInvoke(iasr);
                return ret;
            }

            [XmlRpcEnd]
            public object EndGetValue(IAsyncResult iasr)
            {
                return this.EndInvoke(iasr);
            }

            [XmlRpcBegin("getValue")]
            internal IAsyncResult getValue(string address, string valueKey, AsyncCallback acb)
            {
                return this.BeginInvoke(MethodBase.GetCurrentMethod(), new object[] { address, valueKey }, acb, null);
            }

            [XmlRpcBegin("setValue")]
            internal IAsyncResult setValue(String address, String valueKey, ValueType value, AsyncCallback acb)
            {
                return this.BeginInvoke(MethodBase.GetCurrentMethod(), new object[] { address, valueKey, value }, acb, null);
            }


            public void SetValue(string Address, ValueType Value)
            {
                setValue(Address, "STATE", Value, asr =>
                {
                    ((App)App.Current).RootFrame.Dispatcher.BeginInvoke(delegate()
                    {
                        try
                        {
                            var posts = EndGetValue(asr);
                        }
                        catch (Exception ex)
                        {
                            // Handle exception here
                        }
                    });

                });
            }
        }

        private void bt_loadDevices_Click(object sender, RoutedEventArgs e)
        {
            if (!Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                MessageBox.Show("Keine Netzerkverbindung vorhanden... !", "Verbindungsfehler", MessageBoxButton.OK);
                return;
            }

            bt_loadDevices.IsEnabled = false;
            bt_resetDB.IsEnabled = false;

            try
            {

                tB_PleaseWait.Visibility = System.Windows.Visibility.Visible;
                if (hMDB.DatabaseExists())
                {
                    HMDevices.Clear();
                    hMDB.SubmitChanges();
                    //hMDB.DeleteDatabase();
                }

                if (!hMDB.DatabaseExists())
                {
                    hMDB.CreateDatabase();
                    hMDB.SubmitChanges();
                }

                TB_CCUAddress.IsEnabled = false;
                if (hMDB.HMCCUSettings.Count(t => t.ConfigID == "TEST") == 0)
                {
                    CCUSettings CCUSet = new CCUSettings();
                    CCUSet.ConfigID = "TEST";
                    CCUSet.CCU = TB_CCUAddress.Text;
                    CCUSet.Port = 2000;
                    CCUSet.Modified = DateTime.Now;
                    hMDB.HMCCUSettings.InsertOnSubmit(CCUSet);
                    hMDB.SubmitChanges();
                }

                CCUSettings CCUConf = hMDB.HMCCUSettings.Single(t => t.ConfigID == "TEST");

                proxy = new Homematic();

                proxy.Url = "http://" + CCUConf.CCU + ":" + (CCUConf.Port + 1).ToString();

                #region     Get BidCos RF Devices
                proxy.ListDevices(asr =>
                {
                    ((App)App.Current).RootFrame.Dispatcher.BeginInvoke(delegate()
                    {
                        try
                        {
                            var posts = proxy.EndListDevicesGet(asr);
                            foreach (var post in posts)
                            {
                                Device oResult = new Device();
                                oResult.Bus = "RF";

                                string sType = post["TYPE"].ToString();

                                try
                                {
                                    oResult.Address = post["ADDRESS"].ToString();
                                }
                                catch { }

                                try
                                {
                                    foreach (string sChild in post["CHILDREN"] as string[])
                                    {
                                        Children oChild = new Children();
                                        oChild.ParentAddress = oResult.Address;
                                        oChild.ChildAddress = sChild;
                                        oResult.Childrens.Add(oChild);
                                    }

                                    if (oResult.Childrens == null)
                                    {
                                        oResult.Childrens.ToString();
                                    }


                                }
                                catch { }

                                try
                                {
                                    oResult.Direction = post["DIRECTION"] as int?;
                                }
                                catch { }

                                try
                                {
                                    oResult.Firmware = post["FIRMWARE"].ToString();
                                }
                                catch { }
                                try
                                {
                                    oResult.Parent = post["PARENT"].ToString();
                                }
                                catch { }
                                try
                                {
                                    oResult.ParentType = post["PARENT_TYPE"].ToString();
                                }
                                catch { }
                                try
                                {
                                    oResult.Type = post["TYPE"].ToString();
                                }
                                catch { }

                                try
                                {
                                    oResult.Modified = DateTime.Now;
                                    // Add a to-do item to the observable collection.
                                    if (HMDevices.Count(t => t.Address == oResult.Address) == 0)
                                    {
                                        HMDevices.Add(oResult);

                                        // Add a to-do item to the local database.
                                        hMDB.HMDevices.InsertOnSubmit(oResult);
                                        hMDB.SubmitChanges();
                                    }
                                    else
                                    {
                                        HMDevices.Single(t => t.Address == oResult.Address).Modified = DateTime.Now;
                                        //hMDB.HMDevices.Single(t => t.Address == oResult.Address).Modified = DateTime.Now;
                                        hMDB.SubmitChanges();
                                    }


                                }
                                catch (Exception ex)
                                {
                                    ex.Message.ToString();
                                }
                            }

                        }
                        catch (Exception ex)
                        {
                            // Handle exception here
                        }

                        proxy.Url = "http://" + CCUConf.CCU + ":" + CCUConf.Port.ToString();

                        ListDevices(proxy, CCUConf);
                        //Load additional Details...
                        WebClient oWeb = new WebClient();

                        //oWeb.UploadStringCompleted += new UploadStringCompletedEventHandler(oWeb_UploadStringCompleted);
                        //oWeb.UploadStringAsync(new Uri(@"http://" + CCUConf.CCU + ":8181/Test.exe"), "POST", HMQuery);

                    });
                });

                #endregion

            }
            catch (Exception ex)
            {
                MessageBox.Show("Die Homematic-Zentrale (CCU) ist nicht erreichbar... !", "Verbindungsfehler", MessageBoxButton.OK);
            }
        }

        public void ListDevices(Homematic proxy, CCUSettings CCUConf )
        {
            try
            {
                proxy.ListDevices(asr =>
                {
                    ((App)App.Current).RootFrame.Dispatcher.BeginInvoke(delegate()
                    {
                        try
                        {
                            var posts = proxy.EndListDevicesGet(asr);
                            foreach (var post in posts)
                            {
                                Device oResult = new Device();

                                if (CCUConf.Port == 2000)
                                    oResult.Bus = "Wired";
                                if (CCUConf.Port == 2001)
                                    oResult.Bus = "RF";

                                string sType = post["TYPE"].ToString();

                                try
                                {
                                    oResult.Address = post["ADDRESS"].ToString();
                                }
                                catch { }

                                try
                                {
                                    foreach (string sChild in post["CHILDREN"] as string[])
                                    {
                                        Children oChild = new Children();
                                        oChild.ParentAddress = oResult.Address;
                                        oChild.ChildAddress = sChild;
                                        oResult.Childrens.Add(oChild);
                                    }

                                    if (oResult.Childrens == null)
                                    {
                                        oResult.Childrens.ToString();
                                    }


                                }
                                catch { }

                                try
                                {
                                    oResult.Direction = post["DIRECTION"] as int?;
                                }
                                catch { }

                                try
                                {
                                    oResult.Firmware = post["FIRMWARE"].ToString();
                                }
                                catch { }
                                try
                                {
                                    oResult.Parent = post["PARENT"].ToString();
                                }
                                catch { }
                                try
                                {
                                    oResult.ParentType = post["PARENT_TYPE"].ToString();
                                }
                                catch { }
                                try
                                {
                                    oResult.Type = post["TYPE"].ToString();
                                }
                                catch { }

                                try
                                {
                                    oResult.Modified = DateTime.Now;
                                    // Add a to-do item to the observable collection.
                                    if (HMDevices.Count(t => t.Address == oResult.Address) == 0)
                                    {
                                        HMDevices.Add(oResult);

                                        // Add a to-do item to the local database.
                                        hMDB.HMDevices.InsertOnSubmit(oResult);
                                        hMDB.SubmitChanges();
                                    }
                                    else
                                    {
                                        HMDevices.Single(t => t.Address == oResult.Address).Modified = DateTime.Now;
                                        //hMDB.HMDevices.Single(t => t.Address == oResult.Address).Modified = DateTime.Now;
                                        hMDB.SubmitChanges();
                                    }


                                }
                                catch (Exception ex)
                                {
                                    ex.Message.ToString();
                                }
                            }

                        }
                        catch (Exception ex)
                        {
                            // Handle exception here
                        }

                        //Load additional Details...
                        WebClient oWeb = new WebClient();
                        oWeb.UploadStringCompleted += new UploadStringCompletedEventHandler(oWeb_UploadStringCompleted);
                        oWeb.UploadStringAsync(new Uri(@"http://" + CCUConf.CCU + ":8181/Test.exe"), "POST", HMQuery);
                    });
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show("Die Homematic-Zentrale (CCU) ist auf Port 8181 nicht erreichbar... !", "Verbindungsfehler", MessageBoxButton.OK);
            }
        }

        private void bt_resetDB_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                hMDB.Dispose();

                // Create the database if it does not exist.
                using (HMDataContext db = new HMDataContext(HMDataContext.DBConnectionString))
                {
                    if (db.DatabaseExists() == true)
                    {
                        //Create the database
                        try
                        {
                            db.DeleteDatabase();
                        }
                        catch 
                        {
                            MessageBox.Show("Die Datenbank kann momentan nicht zurückgesetzt werden. \rBitte schliessen Sie die Applikation und versuchen Sie es erneut.", "Fehler", MessageBoxButton.OK);
                        }
                    }
                }

                // Create the database if it does not exist.
                using (HMDataContext db = new HMDataContext(HMDataContext.DBConnectionString))
                {
                    if (db.DatabaseExists() == false)
                    {
                        //Create the database
                        db.CreateDatabase();
                    }
                }

                // Connect to the database and instantiate data context.
                hMDB = new HMDataContext(HMDataContext.DBConnectionString);

                // Data context and observable collection are children of the main page.
                this.DataContext = this;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Die Datenbank kann momentan nicht zurückgesetzt werden. \rBitte schliessen Sie die Applikation und versuchen Sie es erneut.", "Fehler", MessageBoxButton.OK);
            }

        }

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }

        string HMQuery = "string s_device;string s_channel;object o_device;object o_channel;string s_temp;var rooms = \"\";var functions = \"\";string id;" +
        "foreach(s_device, dom.GetObject(ID_DEVICES).EnumUsedIDs()){" +
        "var o_device = dom.GetObject(s_device); WriteLine(o_device.Address()+\":\"+o_device.Name());" +
        "foreach(s_channel, o_device.Channels().EnumUsedIDs()){" +
        "o_channel = dom.GetObject(s_channel);s_temp = \":\" # o_channel.Address();rooms = \"\";" +
        "foreach(id, o_channel.ChnRoom()){" +
        "var room = dom.GetObject(id);rooms = rooms # room.Name() # \"!\";}" +
        "functions = \"\";" +
        "foreach(id, o_channel.ChnFunction()){" +
        "var function = dom.GetObject(id);functions = functions # function.Name() # \"!\";}" +
        "WriteLine(s_temp # \";\" # o_channel.Name() # \";\" # rooms  # \";\" # functions);}}";

        string HMQueryVariables = "string svId;foreach(svId, dom.GetObject(ID_SYSTEM_VARIABLES).EnumIDs()){" +
            "var oSV     = dom.GetObject(svId);" +
            "Write(oSV.ID());" +
            "Write(\"|\" #oSV.Timestamp().ToInteger());" +
            "Write(\"|\" #oSV.Name());" +
            "Write(\"|\" #oSV.Value());" +
            "Write(\"|\" #oSV.Type());" +
            "Write(\"|\" #oSV.ValueSubType());" +
            "Write(\"|\" #oSV.ValueUnit());" +
            "Write(\"|\" #oSV.ValueMin());" +
            "Write(\"|\" #oSV.ValueMax());" +
            "Write(\"|\" #oSV.Visible());" +
            "Write(\"|\" #oSV.DPArchive());" +
            "WriteLine(\"|\" #oSV.ValueList());}";

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Rooms.xaml", UriKind.Relative));
        }


        private void bt_Variablen_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Variables.xaml", UriKind.Relative));
            GetVariables();
        }

        void oWeb_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {

                foreach (string sLine in e.Result.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    try
                    {
                        Boolean bChanel = false;
                        string sName = "";
                        string sName2 = "";
                        string sAddress = "";
                        List<string> lRooms = new List<string>();
                        List<string> lFunctions = new List<string>();

                        if (sLine.StartsWith(":"))
                        {
                            bChanel = true;
                        }

                        if (!bChanel)
                        {
                            sName = sLine.Split(':')[1];
                            sAddress = sLine.Split(':')[0];
                        }
                        else
                        {
                            sName = sLine.Split(';')[1].Split(':')[0];

                            try
                            {
                                sName2 = sLine.Split(';')[1].Split(':')[1];
                                if (int.Parse(sName2) > 0)
                                    sName2 = null;
                            }
                            catch
                            { }

                            sAddress = sLine.Split(':')[1] + ":" + sLine.Split(':')[2].Split(';')[0];

                            //Räume abfüllen....
                            string aRooms = sLine.Split(';')[2];
                            foreach (string sRoom in aRooms.Split('!'))
                            {
                                if (!lRooms.Contains(sRoom) & !string.IsNullOrEmpty(sRoom))
                                {
                                    lRooms.Add(sRoom);
                                    DeviceRoom oDevRoom = new DeviceRoom();
                                    oDevRoom.Address = sAddress;
                                    oDevRoom.RoomName = sRoom;
                                    oDevRoom.Modified = DateTime.Now;

                                    try
                                    {
                                        hMDB.HMRoom.InsertOnSubmit(oDevRoom);
                                        hMDB.SubmitChanges(ConflictMode.ContinueOnConflict);
                                    }
                                    catch { }
                                }
                            }

                            //Functions abfüllen....
                            string aFunctions = sLine.Split(';')[3];
                            foreach (string sFunction in aFunctions.Split('!'))
                            {
                                string sFunc = sFunction.Replace("Verschlu�", "Verschluss");
                                if (!lFunctions.Contains(sFunc) & !string.IsNullOrEmpty(sFunc))
                                {
                                    lFunctions.Add(sFunc);
                                    DeviceFunction oDevFunc = new DeviceFunction();
                                    oDevFunc.Address = sAddress;
                                    oDevFunc.Function = sFunc;
                                    oDevFunc.Modified = DateTime.Now;

                                    try
                                    {
                                        hMDB.HMFunction.InsertOnSubmit(oDevFunc);
                                        hMDB.SubmitChanges(ConflictMode.ContinueOnConflict);
                                    }
                                    catch { }
                                }
                            }


                        }

                        if (hMDB.HMDevices.Count(t => t.Address == sAddress) > 0)
                        {
                            Device oDev = hMDB.HMDevices.Single(t => t.Address == sAddress);
                            sName = sName.Replace('�', 'ü');
                            if (string.IsNullOrEmpty(sName2))
                            {
                                oDev.DisplayName = sName;
                            }
                            else
                            {
                                oDev.DisplayName = sName + ":" + sName2;
                            }
                            //Device oDBDev = hMDB.HMDevices.Single(t => t.Address == sAddress);
                            //oDBDev.DisplayName = sName;
                            try
                            {
                                hMDB.SubmitChanges(ConflictMode.ContinueOnConflict);
                            }
                            catch { }
                        }
                        else
                        {
                            sAddress.ToString();
                        }

                    }
                    catch (Exception ex)
                    {
                        ex.Message.ToString();
                    }

                }

                HMDevices = hMDB.HMDevices.ToObservableCollection();
                bt_loadDevices.IsEnabled = true;
                bt_resetDB.IsEnabled = true;
                tB_PleaseWait.Visibility = System.Windows.Visibility.Collapsed;
                lockablePivot1.SelectedItem = MainPanel;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Die Homematic-Zentrale (CCU) ist nicht erreichbar... !\r(Hinweis: Port 2000,2001 und 8181 werden benötigt).", "Verbindungsfehler", MessageBoxButton.OK);
                TB_CCUAddress.IsEnabled = true;
                bt_loadDevices.IsEnabled = true;
                bt_resetDB.IsEnabled = true;
                tB_PleaseWait.Visibility = System.Windows.Visibility.Collapsed;
            }

            GetVariables();


        }


        private void TB_CCUAddress_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (hMDB.HMCCUSettings.Count(t => t.ConfigID == "TEST") > 0)
                {
                    CCUSettings CCUSet = hMDB.HMCCUSettings.Single(t => t.ConfigID == "TEST");
                    if (CCUSet.CCU != TB_CCUAddress.Text)
                    {
                        CCUSet.CCU = TB_CCUAddress.Text;
                        hMDB.SubmitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButton.OK);
            }
        }

        private void bt_Functions_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Functions.xaml", UriKind.Relative));
        }

        public void GetVariables()
        {
            try
            {
                if (hMDB.HMCCUSettings.Count(t => t.ConfigID == "TEST") == 0)
                {
                    CCUSettings CCUSet = new CCUSettings();
                    CCUSet.ConfigID = "TEST";
                    CCUSet.CCU = TB_CCUAddress.Text;
                    CCUSet.Port = 2000;
                    CCUSet.Modified = DateTime.Now;
                    hMDB.HMCCUSettings.InsertOnSubmit(CCUSet);
                    hMDB.SubmitChanges();
                }

                CCUSettings CCUConf = hMDB.HMCCUSettings.Single(t => t.ConfigID == "TEST");

                //Get Variables
                WebClient oGetVar = new WebClient();
                oGetVar.UploadStringCompleted += new UploadStringCompletedEventHandler(oGetVar_UploadStringCompleted);
                oGetVar.UploadStringAsync(new Uri(@"http://" + CCUConf.CCU + ":8181/Test.exe"), "POST", HMQueryVariables);
            }
            catch
            {

                MessageBox.Show("Die Homematic-Zentrale (CCU) ist nicht erreichbar... !\r(Hinweis: Port 2000,2001 und 8181 werden benötigt).", "Verbindungsfehler", MessageBoxButton.OK);
                TB_CCUAddress.IsEnabled = true;
                bt_loadDevices.IsEnabled = true;
                bt_resetDB.IsEnabled = true;
                tB_PleaseWait.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        void oGetVar_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                foreach (string sLine in e.Result.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (sLine.IndexOf("<xml><exec>") >= 0)
                        continue;
                    try
                    {
                        string[] aVars = sLine.Split('|');
                        sLine.ToString();
                        int ID = int.Parse(aVars[0]);
                        SystemVariable oVar = null;
                        bool bNew = true;
                        if (hMDB.HMVariables_.Count(t => t.ID == ID) != 0)
                        {
                            oVar = hMDB.HMVariables_.Single(t => t.ID == ID);
                            bNew = false;
                        }
                        if (bNew)
                        {
                            oVar = new SystemVariable();
                            oVar.ID = ID;
                        }

                        oVar.Timestamp = new DateTime(1970, 1, 1).AddSeconds(int.Parse(aVars[1]));
                        if (!DateTime.Now.IsDaylightSavingTime())
                            oVar.Timestamp = oVar.Timestamp + new TimeSpan(1, 0, 0);
                        oVar.Name = aVars[2];
                        oVar.Value = aVars[3];
                        oVar.ValueType = int.Parse(aVars[4]);
                        oVar.Subtype = int.Parse(aVars[5]);
                        string sUnit = aVars[6];
                        oVar.Unit = sUnit.Replace('�', '°');
                        oVar.Min = aVars[7];
                        oVar.Max = aVars[8];
                        oVar.Visible = bool.Parse(aVars[9]);
                        oVar.Logged = bool.Parse(aVars[10]);
                        oVar.ValueList = aVars[11];

                        if (bNew)
                        {
                            hMDB.HMVariables_.InsertOnSubmit(oVar);
                        }

                        hMDB.SubmitChanges();
                    }
                    catch (Exception ex)
                    {
                        ex.Message.ToString();
                    }
                }

                HMVariables = hMDB.HMVariables_.ToObservableCollection();
            }
            catch { }
        }


        private void button2_Click(object sender, RoutedEventArgs e)
        {
            GetVariables();
        }



    }
}